<template>
  <div class="file-manager">
    <!-- 顶部操作栏 -->
    <div class="operation-bar">
      <div class="left-actions">
        <el-button 
          type="primary" 
          plain 
          @click="handleBack"
          :disabled="!DataList.folder?.parentId"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回上一级
        </el-button>
      </div>
	  
	  <!-- 当前路径显示 -->
		<div class="current-path">
		  <el-icon><Location /></el-icon>
		  <span>{{ DataList.folder.url }}</span>
		</div>
	  
      <div class="right-actions">
        <el-button type="primary" @click="fileAddRef?.open(DataList.folder)">
          <el-icon><Plus /></el-icon>
          新建
        </el-button>
      </div>
    </div>


    <!-- 文件夹列表 -->
      <div class="folder-section">
        <el-table 
          :data="DataList.folderList" 
          style="width: 100%"
          @row-click="handleFolderClick"
          @row-dblclick="(row) => handleFolderDblClick(row.id)"
          stripe
        >
          <el-table-column prop="name" label="文件名" width="180">
            <template #default="{ row }">
              <el-icon><Folder /></el-icon>
              <span style="margin-left: 10px">{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="permissionType" label="权限">
              <template #default="{ row }">
                <el-tag 
                  :type="getPermissionTagType(row.permissionType)"
                  effect="light"
                  round
                  class="permission-tag"
                >
                  {{ getPermissionLabel(row.permissionType) }}
                </el-tag>
              </template>
            </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="修改时间">
            <template #default="{ row }">
              {{ formatTime(row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button size="small" @click.stop="handleRenameFolder(row)">修改</el-button>
              <el-button size="small" type="danger" @click.stop="handleDeleteFolder(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    
      <!-- 文件列表 -->
      <div class="file-section">
        <el-table :data="DataList.fileList" style="width: 100%" stripe>
          <el-table-column prop="name" label="文件名" width="180">
            <template #default="{ row }">
              <el-icon><Document /></el-icon>
              <span style="margin-left: 10px">{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="permissionType" label="权限">
              <template #default="{ row }">
                <el-tag 
                  :type="getPermissionTagType(row.permissionType)"
                  effect="light"
                  round
                  class="permission-tag"
                >
                  {{ getPermissionLabel(row.permissionType) }}
                </el-tag>
              </template>
            </el-table-column>
          <el-table-column prop="createTime" label="创建时间">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="修改时间">
            <template #default="{ row }">
              {{ formatTime(row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click.stop="handleDownloadFile(row)">下载</el-button>
              <el-button size="small" @click.stop="handleRenameFile(row)">修改</el-button>
              <el-button size="small" type="danger" @click.stop="handleDeleteFile(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
  </div>
  
  
  <!-- 新增信息 -->
  <file-add ref="fileAddRef" @add-ok="content(DataList.folder?.id)"></file-add>
  <!-- 修改 -->
  <file-upd ref="filUpdRef" @udp-ok="content(DataList.folder.id)"></file-upd>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { 
  Document,
  Folder,
  ArrowLeft,
  Plus,
  Location 
} from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import req from '@/request';

//新增
import FileAdd from './fileAdd.vue'
const fileAddRef = ref(null)

//修改
import FileUpd from './fileUpd.vue'
const filUpdRef = ref(null)

// 权限枚举
const permissionTypeOptions = [
  { value: 0, label: '全部可见' },
  { value: 1, label: '部门可见' },
  { value: 2, label: '某个人可见' },
  { value: 3, label: '自己可见' }
]

// 根据权限类型获取中文描述
const getPermissionLabel = (type) => {
  const option = permissionTypeOptions.find(item => item.value === type)
  return option ? option.label : '未知权限'
}

// 权限类型与标签类型的映射
const getPermissionTagType = (type) => {
  const typeMap = {
    0: 'success',  // 全部可见 - 绿色
    1: 'primary',  // 部门可见 - 蓝色
    2: 'warning',  // 某个人可见 - 橙色
    3: 'danger'    // 自己可见 - 红色
  }
  return typeMap[type] || 'info'
}


const updateData = {
	  "type": "",
	  "id": "",
	  "name": "",
	  "permissionType": "",
	  "refId": ""
	}

// 初始化数据结构
const DataList = ref({
  folder: {},
  folderList: [],
  fileList: []
})

// 当前文件夹信息
const currentFolder = ref(null)


// 格式化时间显示
const formatTime = (timeArray) => {
  if (!timeArray) return '-'
  return `${timeArray[0]}-${timeArray[1]}-${timeArray[2]} ${timeArray[3]}:${timeArray[4]}:${timeArray[5]}`
}

const content = async (folderId = null) => {
  try {
    const url = folderId ? `/folder/content?folderId=${folderId}` : '/folder/content'
    const res = await req.get(url)
    
    DataList.value = res.data
    currentFolder.value = res.data.folder
	console.log('currentFolder:',currentFolder.value)
    console.log("获取数据成功:", res.data)
  } catch (error) {
    console.error("请求出错:", error)
  }
}

// 返回上一级
const handleBack = () => {
  if (currentFolder.value?.parentId) {
    content(currentFolder.value.parentId)
  }
}

// 双击文件夹处理
const handleFolderDblClick = (folderId) => {
  content(folderId)
}

// 单击文件夹处理
const handleFolderClick = (folder) => {
  currentFolder.value = folder
}

// 文件夹操作
const handleRenameFolder = (folder) => {
  updateData.value = {
	type: 2,
    id: folder.id,
    name: folder.name,
    permissionType: folder.permissionType,
    refId: folder.refId
  }
  filUpdRef.value?.open(updateData.value)
  content(currentFolder.value?.id)
}

const handleDeleteFolder = async (folder) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文件夹 "${folder.name}" 及其所有内容吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const res = await req.get(`/folder/delete/${folder.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      
      // 优化后的目录刷新逻辑
      if (currentFolder.value?.id === folder.id) {
        // 如果删除的是当前目录本身，则返回上一级
        handleBack()
      } else {
        // 否则刷新当前目录
        content(currentFolder.value?.id)
      }
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message))
    }
  }
}

// 文件操作
const handleDownloadFile = (file) => {
  // 必须由用户点击事件直接触发
  const link = document.createElement('a');
  link.href = `/file/download?fileId=${file.id}`;
  link.download = file.name; 
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const handleRenameFile = (file) => {
  updateData.value = {
	type: 1,
    id: file.id,
    name: file.name,
    permissionType: file.permissionType,
    refId: file.refId
  }
  filUpdRef.value?.open(updateData.value)
  content(currentFolder.value?.id)
}

const handleDeleteFile = async (file) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文件 "${file.name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const res = await req.get(`/file/delete/${file.id}`)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      
      // 确保当前目录存在时才刷新
      if (currentFolder.value) {
        content(currentFolder.value.id)
      } else {
        // 如果当前目录不存在（根目录），则刷新根目录
        content(null)
      }
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.msg || error.message))
    }
  }
}

// 初始化加载
onMounted(() => {
  content(null)
})
</script>

<style scoped>
.file-manager {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.folder-section, .file-section {
  margin-bottom: 30px;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.folder-section {
  margin-bottom: 20px;
}

/* 选中行效果 */
.el-table :deep(.current-row) {
  background-color: #f5f9ff !important;
}

.el-table :deep(.current-row) td {
  border-bottom-color: #409eff !important;
}

/* 防止按钮点击事件冒泡到行 */
.el-button {
  margin: 2px;
}

/* 表格标题样式 */
.el-table :deep(th) {
  background-color: #f8f8f9 !important;
  font-weight: bold;
}

/* 图标与文字间距 */
.el-icon {
  vertical-align: middle;
}

/* 权限标签样式 */
.permission-tag {
  margin: 2px;
  transition: all 0.3s ease;
  font-weight: 500;
}

.permission-tag:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 为不同权限类型添加特定样式 */
.el-tag.el-tag--success {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

.el-tag.el-tag--primary {
  background-color: #f0f7ff;
  border-color: #d9ecff;
  color: #409eff;
}

.el-tag.el-tag--warning {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}

.el-tag.el-tag--danger {
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #f56c6c;
}

.el-tag.el-tag--info {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

/* 导航样式 */
.action-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.current-path {
  flex: 1;
  margin: 0 20px;
  padding: 0 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  height: 32px;
  line-height: 32px;
  display: flex;
  align-items: center;
  color: #666;
}

.current-path .el-icon {
  margin-right: 8px;
  color: var(--el-color-primary);
}
</style>